<template>
  <xn-dialog custom-class="forget-pwd-dialog" title="忘记密码" :visible.sync="selfVisible" @close="onDialogHide">
    <div class="content">
      <div class="tips">
        <el-alert title="若账号未绑定手机号，请联系管理员重置密码！" type="warning" close-text="知道了"></el-alert>
      </div>
      <el-form ref="form" :model="form" label-width="100px" label-suffix="：" :rules="rules">
        <el-form-item label="手机号" prop="telephone">
          <el-input
            v-model="form.telephone"
            placeholder="请输入手机号"
            :maxlength="11"
            clearable
            class="phone-input"
            autocomplete="new-password">
            <template slot="prefix">
              <span class="phone-prefix">+86</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="smCode">
          <el-input
            v-model="form.smCode"
            placeholder="请输入验证码"
            :maxlength="6"
            clearable
            autocomplete="new-password">
            <el-button
              slot="append"
              class="send-btn"
              :class="{ disabled: sendCodeStatus === 'send' }"
              :loading="coding"
              @click="sendCode">
              {{ codeBtnDisplay }}
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-popover trigger="focus" :placement="placement" popper-class="password-tips-popover">
            <div class="password-tip-con">
              <p class="tips-title">密码设置规则</p>
              <p class="tips-con">1. 8~16位数字、字母和特殊符号的组合，至少包含其中两种</p>
              <p class="tips-con">2. 特殊字符包含：!@#$%^&*+=_.()&lt;&gt;?</p>
            </div>
            <el-input
              v-model="form.password"
              slot="reference"
              maxlength="16"
              placeholder="请输入新密码"
              :type="inputStyle"
              show-password
              clearable
              autocomplete="new-password"></el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="确认密码" prop="repeatPwd">
          <el-popover trigger="focus" :placement="placement" popper-class="password-tips-popover">
            <div class="password-tip-con">
              <p class="tips-title">密码设置规则</p>
              <p class="tips-con">1. 8~16位数字、字母和特殊符号的组合，至少包含其中两种</p>
              <p class="tips-con">2. 特殊字符包含：!@#$%^&*+=_.()&lt;&gt;?</p>
            </div>
            <el-input
              v-model="form.repeatPwd"
              slot="reference"
              maxlength="16"
              placeholder="请确认密码"
              :type="inputStyle"
              show-password
              clearable
              autocomplete="new-password"></el-input>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer" slot="footer">
      <el-button type="default" @click="onDialogHide">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </xn-dialog>
</template>
<script>
import { sendSignCode, retrieveLoginPassword } from '@api/modules/user.js'
import XnDialog from '@com/xnDialog.vue'
import { phoneReg, checkCodeReg, pwdReg3 } from '@utility/regExps.js'

export default {
  name: 'ForgetPwdDialog',
  components: {
    XnDialog,
  },
  props: {
    visible: {
      type: Boolean,
    },
  },
  data() {
    const validateNewPwd = (rule, value, callback) => {
      /**
       * 密码规则：1、长度8~16；
       * 2、包含字母及数字；
       * 3、不能和用户名相同。
       */
      if (value === this.form.oldPassword) {
        callback(new Error('新密码不能与原密码相同!'))
      } else if (!pwdReg3.test(value)) {
        callback(new Error('8~16位字母、数字和特殊符号的组合'))
      } else if (value === localStorage.getItem('pskh_loginName')) {
        callback(new Error('不能和用户名相同!'))
      } else {
        callback()
      }
    }
    // 此处即表单发送之前验证  验证新密码与再次确认
    const validatePwdConfirm = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('与新密码不一致!'))
      } else if (!pwdReg3.test(value)) {
        callback(new Error('8~16位字母、数字和特殊符号的组合'))
      } else {
        callback()
      }
    }
    return {
      selfVisible: false,
      isForceEdit: false,
      form: {
        telephone: '',
        smCode: '',
        password: '',
        repeatPwd: '',
      },
      rules: {
        // 验证规则
        telephone: [
          {
            required: true,
            message: '请输入有效的手机号',
            trigger: 'blur',
            pattern: phoneReg,
          },
        ],
        smCode: [
          {
            required: true,
            message: '请输入有效的验证码',
            trigger: 'blur',
            pattern: checkCodeReg,
          },
        ],
        password: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur',
          },
          {
            validator: validateNewPwd,
            trigger: 'blur',
          },
        ],
        repeatPwd: [
          {
            required: true,
            message: '请确认新密码',
            trigger: 'blur',
          },
          {
            validator: validatePwdConfirm,
            trigger: 'blur',
          },
        ],
      },
      cutdownSec: 0,
      sendCodeStatus: 'init', // init, send, retry
      cutdownTimer: null,
      coding: false,
      placement: 'right',
      inputStyle: 'text',
    }
  },
  computed: {
    codeBtnDisplay() {
      if (this.sendCodeStatus === 'init') {
        return '发送验证码'
      } else if (this.sendCodeStatus === 'send') {
        return this.cutdownSec + ' 秒'
      }
      return '重新发送'
    },
    userInfo() {
      return this.$store.getters['role/userInfo']
    },
  },
  watch: {
    visible(visible) {
      this.selfVisible = visible
      if (visible) {
        this.watchWindowSize()
      }
    },
  },
  mounted() {
    window.addEventListener('resize', this.watchWindowSize)
    console.log('123456 :>> ', 123456)
    this.$nextTick(() => {
      setTimeout(() => {
        this.inputStyle = 'password'
      }, 100)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.watchWindowSize)
  },
  methods: {
    watchWindowSize() {
      const wW = document.documentElement.clientWidth
      if (wW > 1250) {
        this.placement = 'right'
      } else {
        this.placement = 'top'
      }
    },
    onDialogHide() {
      this.$refs.form && this.$refs.form.resetFields()
      this.form = {
        telephone: '',
        smCode: '',
        password: '',
        repeatPwd: '',
      }
      this.clearCutdownTimer()
      this.sendCodeStatus = 'init'
      this.selfVisible = false
      this.$emit('update:visible', false)
      this.$emit('closed')
    },
    sendCode() {
      if (this.coding || this.sendCodeStatus === 'send') {
        return
      }
      this.$refs.form.validateField('telephone', async invalid => {
        if (!invalid) {
          this.coding = true
          const { data, status } = await sendSignCode(this.form.telephone, '1')
          this.coding = false
          if (data === 'SUCCESS' || status === 200) {
            this.startCutdown()
          }
        }
      })
    },
    startCutdown() {
      this.clearCutdownTimer()
      this.sendCodeStatus = 'send'
      this.cutdownSec = 60
      this.cutdownTimer = setInterval(() => {
        this.cutdownSec--
        if (this.cutdownSec <= 0) {
          this.clearCutdownTimer()
          this.sendCodeStatus = 'retry'
        }
      }, 1000)
    },
    clearCutdownTimer() {
      if (this.cutdownTimer) {
        clearInterval(this.cutdownTimer)
      }
    },
    onSubmit() {
      console.log('onSubmit...')
      this.$refs.form.validate(valid => {
        // valid 全为 true即执行以下操作
        if (valid) {
          retrieveLoginPassword(this.form).then(res => {
            if (res.code === 0 || res.status === 200) {
              this.$message.success('重置密码成功！')
              this.onDialogHide()
              this.userInfo.telephone = this.form.telephone
              this.$store.commit('role/setUserInfo', this.userInfo)
            }
          })
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.forget-pwd-dialog {
  ::v-deep &.el-dialog {
    width: 500px !important;

    .content {
      height: 100%;
      padding-top: 10px;
      padding-right: 20px;

      .phone-input {
        input {
          padding-left: 45px;
        }
        .phone-prefix {
          padding-left: 5px;
        }
        .el-input__prefix {
          display: flex;
          align-items: center;
        }
      }

      .tips {
        margin-bottom: 20px;
        padding-left: 20px;
      }

      .el-input-group__append {
        color: #fff;
        background: linear-gradient(0deg, #0074f4 0%, #2099ff 100%);
        border-right: none;
      }

      .send-btn {
        width: 120px;

        &.disabled {
          cursor: not-allowed;
        }
      }

      .footer {
        text-align: center;

        .btn-sure {
          padding: 10px 50px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-popover {
  &.password-tips-popover {
    .password-tip-con {
      .tips-title {
        font-size: 15px;
        list-style: 24px;
        margin-bottom: 10px;
        color: #333;
      }

      .tips-con {
        font-size: 13px;
        list-style: 20px;
        margin-bottom: 5px;
        color: #666;
      }
    }
  }
}
</style>
